package com.power.sifa.util;

import cn.hutool.core.util.ObjectUtil;
import com.plf.common.cache.CacheManager;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName CacheHelper
 * @Author xiongzw
 * @Date 2023/10/17 16:31
 * @Description
 * @Version: 1.0
 **/

@Component
public class CacheHelper {

    @Resource
    private CacheManager cacheManager;

    /**
     * 电子卷宗的文本paper读取页数
     */
    public static final String CACHE_PAMPER = "CACHE:PAMPER";

    /**
     * 送达回执
     */
    public static final String CACHE_RECEIPT = "CACHE:RECEIPT";


    /**
     * 根据文件id来获取对应的文本的页数
     *
     * @param attachId
     * @return
     */
    public Integer findFileIndex(String attachId) {
        Map<String, Integer> paperMap = (Map<String, Integer>) cacheManager.get(CACHE_PAMPER);
        if (ObjectUtil.isNotNull(paperMap) && paperMap.containsKey(attachId)) {
            return paperMap.get(attachId);
        }
        return null;
    }

    /**
     * 将读取的文件页数读取到缓存中，避免多次读取远程文件重新读页数。
     *
     * @param attachId
     * @param paperIndex
     */
    public void setFileIndex(String attachId, Integer paperIndex) {
        Map<String, Integer> paperMap = (Map<String, Integer>) cacheManager.get(CACHE_PAMPER);
        if (ObjectUtil.isNull(paperMap)) {
            paperMap = new HashMap<>();
        }
        paperMap.put(attachId, paperIndex);
        // 设置30天的有效期
        cacheManager.put_temp(CACHE_PAMPER, (Serializable) paperMap, 30 * 24 * 60 * 60);
    }

    /**
     * 获取电子送达验证失败次数
     *
     * @param code 案号
     * @return
     */
    public Integer getReceiptCount(String code) {
        final String cacheKey = CACHE_RECEIPT + "_" + code;
        Map<String, Integer> paperMap = (Map<String, Integer>) cacheManager.get(cacheKey);
        if (ObjectUtil.isNotNull(paperMap) && paperMap.containsKey(code)) {
            return paperMap.get(code);
        }
        return 0;
    }

    /**
     * 设置电子送达验证失败次数
     *
     * @param code 案号
     * @param count     校验过的次数
     */
    public void setReceiptCount(String code, Integer count) {
        final String cacheKey = CACHE_RECEIPT + "_" + code;
        Map<String, Integer> paperMap = (Map<String, Integer>) cacheManager.get(cacheKey);
        if (ObjectUtil.isNull(paperMap)) {
            paperMap = new HashMap<>();
        }
        paperMap.put(code, count);
        cacheManager.put_temp(cacheKey, (Serializable) paperMap, 300);
    }


}
